package com.example.controlleradvice;

import com.example.controlleradvice.globalDataPreprocessor.Author;
import com.example.controlleradvice.globalDataPreprocessor.Book;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.util.Map;

/**
 * @author: 李明杰
 * @date: 2022/6/6 12:26
 */
@RestController
@Slf4j
public class StartController {

    /**
     * 全局数据预处理(两个接收对象的属性名都一样，需要数据预处理)
     *
     * @param book
     * @param author
     */
    @GetMapping("/processor")
    public void globalDataPreprocessor(@ModelAttribute("b") Book book, @ModelAttribute("a") Author author) {
//        http://localhost:8080/processor?b.name=西游记&b.price=199&a.name=吴承恩&a.age=18
        log.error(book.toString());
        log.error(author.toString());
    }

    //    全局数据绑定
    @GetMapping("/binder")
    public void hello(@ModelAttribute("msg") String msg,
                      @ModelAttribute("info") Map<String, String> info,
                      Model model) {
        Map<String, Object> map = model.asMap();
        String fromModel = map.get("info").toString();
        log.error("The data from model,it's values={}", fromModel);
        log.error("@ModelAttribute(\"msg\") String msg={}", info);
        log.error("@ModelAttribute(\"info\") Map<String, String> info={}", info);

    }


    //    全局异常处理
    @GetMapping("/exception")
    public Integer a() throws SQLException {
//        throwRuntimeException();
        throwNotRunTimeException();
        return 0;
    }

    private Integer throwNotRunTimeException() throws SQLException {
        throw new SQLException();
    }

    private Integer throwRuntimeException() {
        throw new RuntimeException();
    }
}
